package com.nx.platform.es.system.utils;

import com.google.common.collect.Iterables;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author
 * @date 2018/03/22
 */
public class IPUtil {

    private static final Logger LOGGER = LogManager.getLogger(IPUtil.class);
    private static final String ETH0 = "eth0";
    private static final Pattern IP = Pattern.compile("\\d++\\.\\d++\\.(\\d++\\.\\d++)");

    public static Optional<String> getLocalHostIp() {
        InetAddress address = null;
        try {
            Map<String, InetAddress> addresses = getLocalHostSiteLocalAddresses();
            LOGGER.info("getLocalHostIp, addresses={}", addresses);
            address = addresses.getOrDefault(ETH0, Iterables.getFirst(addresses.values(), null));
        } catch (SocketException e) {
            LOGGER.error("getLocalHostIp error", e);
        }
        String ip = address != null ? address.getHostAddress() : null;
        LOGGER.info("getLocalHostIp, ip={}", ip);
        return Optional.ofNullable(ip);
    }

    public static String getIpLast2Field(String ip) throws IllegalArgumentException {
        Matcher matcher = IP.matcher(ip);
        if (matcher.find()) {
            return matcher.group(1).replaceAll("\\.", "");
        } else {
            throw new IllegalArgumentException("ip=" + ip);
        }
    }
    /**
     * 获取所在服务器ip
     *
     * @return :
     * @description :
     * @author : tianwei
     * @date : 2018/3/6
     */
    public static String getLocalServerIP() {
        String ipStr = null;
        InetAddress ip = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface
                    .getNetworkInterfaces();//所有网络接口，包括物理和虚拟的
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                //只需要eth0 网卡的ip 。   tianwei
                if (!ni.getName().contains("eth0")) {
                    continue;
                }
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = ips.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().matches(
                            "(\\d{1,3}\\.){3}\\d{1,3}")) {//// 非127.0.0.1
                        break;
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error(" act=getLocalServerIP ex={}", e.getMessage());
        }
        if (null != ip) {
            ipStr = ip.getHostAddress();
        }
        LOGGER.info(" act=getLocalServerIP ip={}", ipStr);
        return ipStr;
    }

    private static Map<String, InetAddress> getLocalHostSiteLocalAddresses() throws SocketException {
        Map<String, InetAddress> map = new LinkedHashMap<>();
        Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        while (networks.hasMoreElements()) {
            NetworkInterface network = networks.nextElement();
            Enumeration<InetAddress> addresses = network.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address.isSiteLocalAddress()) {
                    map.put(network.getName(), address);
                    break;
                }
            }
        }
        return map;
    }

}
